import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, StatusBar, TouchableWithoutFeedback, Keyboard, ScrollView } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons, MaterialIcons } from '@expo/vector-icons';
import { router } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

// 忘记密码页面组件
export default function ForgotPasswordScreen() {
  const insets = useSafeAreaInsets(); // 获取安全区域的尺寸
  
  // 状态管理
  const [step, setStep] = useState(0); // 0: 验证身份, 1: 重置密码, 2: 成功
  const [verificationMethod, setVerificationMethod] = useState('email'); // 'email' 或 'phone'
  const [studentId, setStudentId] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  // 发送验证码
  const sendVerificationCode = () => {
    if (verificationMethod === 'email' && !email) {
      Alert.alert('提示', '请输入注册时使用的邮箱地址');
      return;
    }
    
    if (verificationMethod === 'phone' && !phone) {
      Alert.alert('提示', '请输入注册时使用的手机号码');
      return;
    }
    
    // 提示验证码为1234
    Alert.alert(
      '验证码已发送',
      '您的验证码是: 1234（测试阶段固定值）',
      [{ text: '确定', style: 'default' }]
    );
  };
  
  // 下一步按钮处理
  const handleNext = () => {
    if (step === 0) {
      // 验证身份
      if (verificationMethod === 'email' && (!email || !verificationCode)) {
        Alert.alert('提示', '请填写邮箱和验证码');
        return;
      }
      
      if (verificationMethod === 'phone' && (!phone || !verificationCode)) {
        Alert.alert('提示', '请填写手机号码和验证码');
        return;
      }
      
      if (verificationCode !== '1234') {
        Alert.alert('提示', '验证码不正确');
        return;
      }
      
      setStep(1); // 进入重置密码步骤
    } else if (step === 1) {
      // 重置密码
      if (!newPassword || !confirmPassword) {
        Alert.alert('提示', '请输入新密码和确认密码');
        return;
      }
      
      if (newPassword !== confirmPassword) {
        Alert.alert('提示', '两次输入的密码不一致');
        return;
      }
      
      setStep(2); // 进入成功步骤
    }
  };
  
  // 渲染验证身份步骤
  const renderVerificationStep = () => {
    return (
      <ScrollView style={styles.formContainer} showsVerticalScrollIndicator={false}>
        {/* 验证方式选择器 */}
        <View style={styles.tabContainer}>
          <TouchableOpacity 
            style={[styles.tab, verificationMethod === 'email' && styles.activeTab]} 
            onPress={() => setVerificationMethod('email')}
          >
            <Text style={[styles.tabText, verificationMethod === 'email' && styles.activeTabText]}>邮箱验证</Text>
          </TouchableOpacity>
          <TouchableOpacity 
            style={[styles.tab, verificationMethod === 'phone' && styles.activeTab]}
            onPress={() => setVerificationMethod('phone')}
          >
            <Text style={[styles.tabText, verificationMethod === 'phone' && styles.activeTabText]}>手机验证</Text>
          </TouchableOpacity>
        </View>
        
        {verificationMethod === 'email' ? (
          // 邮箱验证表单
          <View>
            <View style={styles.inputGroup}>
              <Text style={styles.label}>注册邮箱</Text>
              <View style={styles.inputContainer}>
                <MaterialIcons name="email" size={20} color="#888" style={styles.inputIcon} />
                <TextInput
                  style={styles.input}
                  placeholder="请输入您注册时使用的邮箱地址"
                  keyboardType="email-address"
                  value={email}
                  onChangeText={setEmail}
                />
              </View>
            </View>
            
            <View style={styles.inputGroup}>
              <Text style={styles.label}>验证码</Text>
              <View style={styles.verificationContainer}>
                <View style={[styles.inputContainer, styles.verificationInput]}>
                  <MaterialIcons name="security" size={20} color="#888" style={styles.inputIcon} />
                  <TextInput
                    style={styles.input}
                    placeholder="请输入验证码"
                    keyboardType="numeric"
                    maxLength={4}
                    value={verificationCode}
                    onChangeText={setVerificationCode}
                  />
                </View>
                <TouchableOpacity style={styles.verificationButton} onPress={sendVerificationCode}>
                  <Text style={styles.verificationButtonText}>获取验证码</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        ) : (
          // 手机验证表单
          <View>
            <View style={styles.inputGroup}>
              <Text style={styles.label}>手机号码</Text>
              <View style={styles.inputContainer}>
                <MaterialIcons name="phone" size={20} color="#888" style={styles.inputIcon} />
                <TextInput
                  style={styles.input}
                  placeholder="请输入您注册时使用的手机号码"
                  keyboardType="phone-pad"
                  value={phone}
                  onChangeText={setPhone}
                />
              </View>
            </View>
            
            <View style={styles.inputGroup}>
              <Text style={styles.label}>验证码</Text>
              <View style={styles.verificationContainer}>
                <View style={[styles.inputContainer, styles.verificationInput]}>
                  <MaterialIcons name="security" size={20} color="#888" style={styles.inputIcon} />
                  <TextInput
                    style={styles.input}
                    placeholder="请输入验证码"
                    keyboardType="numeric"
                    maxLength={4}
                    value={verificationCode}
                    onChangeText={setVerificationCode}
                  />
                </View>
                <TouchableOpacity style={styles.verificationButton} onPress={sendVerificationCode}>
                  <Text style={styles.verificationButtonText}>获取验证码</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        )}

        {/* 下一步按钮 */}
        <TouchableOpacity style={styles.nextButton} onPress={handleNext}>
          <Text style={styles.nextButtonText}>下一步</Text>
        </TouchableOpacity>
        
        {/* 记住密码? 返回登录 */}
        <View style={styles.footerContainer}>
          <Text style={styles.footerText}>记起密码了? </Text>
          <TouchableOpacity onPress={() => router.replace('/login')}>
            <Text style={styles.footerLink}>返回登录</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    );
  };
  
  // 渲染重置密码步骤
  const renderResetPasswordStep = () => {
    return (
      <ScrollView style={styles.formContainer} showsVerticalScrollIndicator={false}>
        <Text style={styles.resetTitle}>重置密码</Text>
        <Text style={styles.resetSubtitle}>请设置您的新密码</Text>

        {/* 新密码输入框 */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>新密码</Text>
          <View style={styles.inputContainer}>
            <Ionicons name="lock-closed" size={20} color="#888" style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="请设置新密码"
              secureTextEntry={!showNewPassword}
              value={newPassword}
              onChangeText={setNewPassword}
            />
            <TouchableOpacity 
              style={styles.passwordToggle}
              onPress={() => setShowNewPassword(!showNewPassword)}
            >
              <Ionicons name={showNewPassword ? "eye" : "eye-off"} size={20} color="#888" />
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 确认新密码输入框 */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>确认新密码</Text>
          <View style={styles.inputContainer}>
            <Ionicons name="lock-closed" size={20} color="#888" style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="请再次输入新密码"
              secureTextEntry={!showConfirmPassword}
              value={confirmPassword}
              onChangeText={setConfirmPassword}
            />
            <TouchableOpacity 
              style={styles.passwordToggle}
              onPress={() => setShowConfirmPassword(!showConfirmPassword)}
            >
              <Ionicons name={showConfirmPassword ? "eye" : "eye-off"} size={20} color="#888" />
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 提交按钮 */}
        <TouchableOpacity style={styles.nextButton} onPress={handleNext}>
          <Text style={styles.nextButtonText}>确认修改</Text>
        </TouchableOpacity>
      </ScrollView>
    );
  };
  
  // 渲染成功步骤
  const renderSuccessStep = () => {
    return (
      <View style={styles.successContainer}>
        <View style={styles.successIconContainer}>
          <Ionicons name="checkmark-circle" size={80} color="#4CAF50" />
        </View>
        <Text style={styles.successTitle}>密码重置成功</Text>
        <Text style={styles.successMessage}>您的密码已成功重置，请使用新密码登录</Text>
        <TouchableOpacity 
          style={styles.loginButton} 
          onPress={() => router.replace('/login')}
        >
          <Text style={styles.loginButtonText}>返回登录</Text>
        </TouchableOpacity>
      </View>
    );
  };
  
  // 渲染步骤指示器
  const renderStepIndicator = () => {
    return (
      <View style={styles.stepIndicator}>
        <View style={styles.stepItem}>
          <View style={[styles.stepCircle, step >= 0 ? styles.activeStepCircle : {}]}>
            <MaterialIcons name="email" size={20} color={step >= 0 ? "#fff" : "#888"} />
          </View>
          <Text style={styles.stepText}>验证身份</Text>
        </View>
        <View style={styles.stepConnector} />
        <View style={styles.stepItem}>
          <View style={[styles.stepCircle, step >= 1 ? styles.activeStepCircle : {}]}>
            <Ionicons name="lock-closed" size={20} color={step >= 1 ? "#fff" : "#888"} />
          </View>
          <Text style={styles.stepText}>重置密码</Text>
        </View>
        <View style={styles.stepConnector} />
        <View style={styles.stepItem}>
          <View style={[styles.stepCircle, step >= 2 ? styles.activeStepCircle : {}]}>
            <Ionicons name="checkmark" size={20} color={step >= 2 ? "#fff" : "#888"} />
          </View>
          <Text style={styles.stepText}>完成</Text>
        </View>
      </View>
    );
  };

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <View style={styles.container}>
        <StatusBar barStyle="light-content" />
        
        {/* 顶部渐变背景区域 */}
        <LinearGradient
          colors={['#9c27b0', '#5e35b1', '#3949ab']}
          style={[
            styles.header,
            { paddingTop: insets.top + 20 } // 添加顶部安全区域的padding
          ]}
        >
          <TouchableOpacity 
            style={styles.backButton}
            onPress={() => {
              if (step > 0) {
                setStep(step - 1);
              } else {
                router.replace('/login');
              }
            }}
          >
            <Ionicons name="arrow-back" size={24} color="#ffffff" />
            <Text style={styles.backButtonText}>{step > 0 ? '返回上一步' : '返回登录'}</Text>
          </TouchableOpacity>
          
          <View style={styles.headerTextContainer}>
            <Text style={styles.welcomeText}>找回密码</Text>
            <Text style={styles.subHeaderText}>我们将帮您重新设置密码</Text>
          </View>
          
          {/* 步骤指示器 */}
          {renderStepIndicator()}
        </LinearGradient>

        {/* 根据当前步骤渲染不同内容 */}
        {step === 0 && renderVerificationStep()}
        {step === 1 && renderResetPasswordStep()}
        {step === 2 && renderSuccessStep()}
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9f9f9',
  },
  header: {
    minHeight: 220,
    paddingHorizontal: 24,
  },
  backButton: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  backButtonText: {
    color: '#ffffff',
    fontSize: 16,
    marginLeft: 8,
  },
  headerTextContainer: {
    marginBottom: 24,
  },
  welcomeText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#ffffff',
    marginBottom: 8,
  },
  subHeaderText: {
    fontSize: 16,
    color: 'rgba(255, 255, 255, 0.8)',
  },
  formContainer: {
    flex: 1,
    backgroundColor: '#ffffff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    marginTop: -20,
    paddingHorizontal: 24,
    paddingTop: 24,
  },
  tabContainer: {
    flexDirection: 'row',
    marginBottom: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  tab: {
    flex: 1,
    paddingBottom: 12,
    alignItems: 'center',
  },
  activeTab: {
    borderBottomWidth: 2,
    borderBottomColor: '#5e35b1',
  },
  tabText: {
    fontSize: 16,
    color: '#888',
  },
  activeTabText: {
    color: '#5e35b1',
    fontWeight: '500',
  },
  inputGroup: {
    marginBottom: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 8,
    color: '#333',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    backgroundColor: '#f9f9f9',
    height: 50,
  },
  inputIcon: {
    paddingHorizontal: 12,
  },
  input: {
    flex: 1,
    height: 50,
    fontSize: 16,
    color: '#333',
  },
  passwordToggle: {
    padding: 12,
  },
  verificationContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  verificationInput: {
    flex: 2,
    marginRight: 10,
  },
  verificationButton: {
    height: 50,
    backgroundColor: '#5e35b1',
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 15,
    flex: 1,
  },
  verificationButtonText: {
    color: '#fff',
    fontWeight: '500',
    fontSize: 14,
  },
  nextButton: {
    backgroundColor: '#5e35b1',
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  nextButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
  footerContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 24,
    marginBottom: 20,
  },
  footerText: {
    fontSize: 14,
    color: '#666',
  },
  footerLink: {
    fontSize: 14,
    color: '#5e35b1',
    fontWeight: '500',
  },
  resetTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  resetSubtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 24,
  },
  successContainer: {
    flex: 1,
    backgroundColor: '#ffffff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    marginTop: -20,
    paddingHorizontal: 24,
    paddingTop: 40,
    alignItems: 'center',
  },
  successIconContainer: {
    backgroundColor: 'rgba(76, 175, 80, 0.1)',
    width: 120,
    height: 120,
    borderRadius: 60,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 24,
  },
  successTitle: {
    fontSize: 22,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  successMessage: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    marginBottom: 32,
    paddingHorizontal: 20,
  },
  loginButton: {
    backgroundColor: '#5e35b1',
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 32,
    marginTop: 10,
  },
  loginButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
  stepIndicator: {
    flexDirection: 'row',
    marginTop: 16,
    alignItems: 'center',
    justifyContent: 'center',
  },
  stepItem: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  stepCircle: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 6,
  },
  activeStepCircle: {
    backgroundColor: '#4CAF50',
  },
  stepText: {
    color: 'white',
    fontSize: 12,
  },
  stepConnector: {
    height: 2,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    flex: 1,
    marginHorizontal: 8,
  },
}); 